<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue';
import { Global } from "../../Global";
import { HttpHelper } from "../../lib/HttpHelper";
import { ElTable, ElForm } from 'element-plus';

const isLoading = ref(false);
const isBusy = ref(false);
const listDatas = ref(<any[]>[]);
const pageNumber = ref(1);
const servicePath = "/SystemMenu";
const total = ref(0);
const formData = ref(<any>{});
var editingData: any;
const dialogFormVisible = ref(false);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<any[]>([]);
const formRef = ref<InstanceType<typeof ElForm>>();

    const topLevelId = 0;

var parentRow: any;
const rules = reactive({
  "Caption": [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ]
})

onMounted(() => {
  bindList();
});


const refreshClick = () => {
  bindList();
}

const setDatasChildren = (allItems: any[], parentId: any) => {
  var ret = allItems.filter(x => x.ParentId == parentId);
  ret.forEach(item => {
    item.children = setDatasChildren(allItems, item.id);
    item.children.forEach((x: any) => {
      x.parentItems = item.children;

    });
  });
  return ret;
}

const bindList = async () => {
  isLoading.value = true;
  try {
    var list = JSON.parse(await HttpHelper.postJson(`${servicePath}/List`, {
      PageIndex: pageNumber.value - 1,
      PageSize: 10,
    }));

    list.Datas = setDatasChildren(list.Datas, topLevelId);
    list.Datas.forEach((x: any) => {
      x.parentItems = listDatas.value;

    });

    total.value = list.Total;
    listDatas.value.splice(0, listDatas.value.length);
    listDatas.value.push(...list.Datas);

    if (listDatas.value.length == 0 && pageNumber.value > 1) {
      pageNumber.value--;
      bindList();
    }
  } catch (error) {
    Global.showError(error);
  }
  finally {
    isLoading.value = false;
  }
}

const resetFormData = () => {
  formData.value = {
    Name: {
      zhCN: "",
      enUS: ""
    },
    ParentId: topLevelId,
    Sort: 0,
    Status: 100,
    Desc: "",
    Pic: "",
    IsHome: false
  };
}

const addClick = () => {
  resetFormData();
  parentRow = null;
  dialogFormVisible.value = true;
}

const addSubClick = (row: any) => {
  resetFormData();
  parentRow = row;
  formData.value.ParentId = row.id;
  dialogFormVisible.value = true;
}

const editClick = (row: any) => {
  resetFormData();
  for (var p in row) {
    if (p != "parentItems" && p != "children") {
      formData.value[p] = row[p];
    }
  }
  editingData = row;
  dialogFormVisible.value = true;
}

const deleteClick = async () => {
  if (isLoading.value)
    return;

  if (multipleSelection.value.length == 0) {
    Global.showInfo("请选择需要删除的数据");
    return;
  }

  if (confirm("确定删除吗？")) {
    try {
      isLoading.value = true;
      var requestData = new FormData();
      multipleSelection.value.forEach(x => {
        requestData.append("ids", x.id);

      });
      await HttpHelper.postFormData(`${servicePath}/Delete`, requestData);
      multipleSelection.value.forEach(x => {
        var index = x.parentItems.indexOf(x);
        if (index >= 0) {
          x.parentItems.splice(index, 1);
        }

      });
      multipleTableRef.value?.clearSelection();
    } catch (error) {
      Global.showError(error);
    }
    finally {
      isLoading.value = false;
    }
  }
}

const handleSelectionChange = (selecteds: any[]) => {
  multipleSelection.value = selecteds;
}

const insertToParent = (item: any, parentItems: any[]) => {
  item.parentItems = parentItems;
  for (var i = parentItems.length - 1; i >= 0; i--) {
    var other = parentItems[i];
    if (item.Sort >= other.Sort) {
      parentItems.splice(i + 1, 0, item);
      return;
    }
  }
  parentItems.splice(0,0,item);
}

const submitClick = async () => {
  try {
    await formRef.value?.validate();
  } catch (error) {
    return;
  }

  try {
    isBusy.value = true;
    if (formData.value.id) {
      var newParentChildren: any = null;

      if (formData.value.ParentId && Array.isArray(formData.value.ParentId)) {
        //查找最新的上级对象
        newParentChildren = listDatas.value;

        for (var i = 0; i < formData.value.ParentId.length; i++) {
          var pid = formData.value.ParentId[i];
          var item = newParentChildren.find((x: any) => x.id == pid);
          newParentChildren = item.children;
        }
        formData.value.ParentId = formData.value.ParentId[formData.value.ParentId.length - 1];

      }
      else if(formData.value.ParentId == topLevelId && editingData.ParentId){
        newParentChildren = listDatas.value;
      }

      await HttpHelper.postJson(`${servicePath}/Modify`, formData.value);
      var sortChanged = editingData.Sort != formData.value.Sort;
      console.log("排序变化吗", sortChanged);

      for (var p in formData.value) {
        editingData[p] = formData.value[p];
      }

      if (sortChanged || newParentChildren) {
        var index = editingData.parentItems.indexOf(editingData);
        editingData.parentItems.splice(index, 1);
        console.log("先删除", index);

        if (newParentChildren)
          editingData.parentItems = newParentChildren;

        insertToParent(editingData, editingData.parentItems);
      }
    }
    else {
      var id = await HttpHelper.postJson(`${servicePath}/Add`, formData.value);
      formData.value.id = id;
      formData.value.children = [];

      if (parentRow) {
        insertToParent(formData.value, parentRow.children);
      }
      else {
        insertToParent(formData.value, listDatas.value);
      }
    }
    dialogFormVisible.value = false;
  } catch (error) {
    Global.showError(error);
  }
  finally {
    isBusy.value = false;

  }
}

</script>
<template>
  <div class="page-view-main">
    <div style="padding: var(--page-padding);flex:1;min-height:0px;display: flex;flex-direction: column;">
      <div class="page-view-panel">
        <div style="display: flex;justify-content: end;margin-bottom: 10px;">
          <el-button-group class="ml-4">
            <el-button type="default" icon="Plus" @click="addClick">添加一级菜单</el-button>
            <el-button type="default" icon="Refresh" @click="refreshClick">刷新</el-button>
            <el-button type="default" icon="Delete" @click="deleteClick">删除</el-button>
          </el-button-group>
        </div>

        <el-table ref="multipleTableRef" @selection-change="handleSelectionChange" :data="listDatas" row-key="id"
           cell-class-name="tb-cell" header-cell-class-name="tb-header-cell"
          table-layout="auto" v-loading="isLoading" style="flex:1;min-height:0px;">
          <el-table-column type="selection" width="42" fixed="left" />
          <el-table-column prop="Caption" label="名称" />
          <el-table-column prop="Code" label="标识" />
          <el-table-column prop="Sort" label="排序" />
          <el-table-column prop="Icon" label="图标" />
          <el-table-column prop="Path" label="路径" />
          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <el-button size="small" type="primary" @click="editClick(scope.row)">
                编辑
              </el-button>
              <el-button size="small" type="warning" @click="addSubClick(scope.row)">
                添加子菜单
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog v-model="dialogFormVisible" :title="formData.id ? '编辑' : '新增'" :close-on-click-modal="false" width="500">
      <el-form ref="formRef" :model="formData" label-width="auto" :rules="rules"
        @keypress.native.enter.prevent="submitClick">
        <el-form-item label="上级菜单" v-if="formData.id">
          <el-cascader :options="listDatas" v-model="formData.ParentId"
            :props="{ checkStrictly: true, label:'Caption', value: 'id' }" clearable>
          </el-cascader>
          <el-button type="primary" @click="formData.ParentId=topLevelId">放到顶级</el-button>
        </el-form-item>
        <el-form-item label="名称" prop="Caption">
          <el-input v-model="formData.Caption" />
        </el-form-item>
        <el-form-item label="标识" prop="Code">
          <el-input v-model="formData.Code" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="formData.Sort" />
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="formData.Icon" />
        </el-form-item>
        <el-form-item label="路径">
          <el-input v-model="formData.Path" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" :loading="isBusy" @click="submitClick">
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">

.uploadItem {
  position: relative;

  img {
    width: 126px;
    height: 126px;
  }

  input {
    position: absolute;
    cursor: pointer;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
  }

  .uploadBorder {
    width: 126px;
    height: 126px;
    font-size: 30px;
    color: #eee;
    border-radius: 5px;
    border: 1px solid #eee;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>